package com.bubbo.discoverCenterImpl;

import com.bubbo.discoverCenter.ServiceDiscover;
import com.bubbo.rpc.client.util.CollectionUtil;
import com.bubbo.rpc.client.util.zkConstent;
import io.netty.util.internal.StringUtil;
import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by waasdasd on 2017/4/7.
 */
public class ServiceDiscoverImpl implements ServiceDiscover {
    private static final Logger logger = LoggerFactory.getLogger(ServiceDiscoverImpl.class);

    private final ZkClient zkClient;


    public ServiceDiscoverImpl(String address) {
        this.zkClient = new ZkClient(address, 5000, 1000);
        logger.debug("connect.......");
    }

    @Override
    public String discovery(String serviceName) {
        String addressPath = "";
        try {
            logger.debug("connect....");
            String servicePath = zkConstent.ZK_REGISTRY_PATH + "/" + serviceName + "/providers";
            if (!zkClient.exists(servicePath)) {
                throw new RuntimeException(String.format("can not find any service node on path: %s", servicePath));
            }
            addressPath = zkClient.readData(servicePath);
            if (StringUtils.isEmpty(servicePath)) {
                throw new RuntimeException(String.format("don't have any service %s", servicePath));
            }
        } catch (RuntimeException ex) {
            ex.printStackTrace();
        }
        return addressPath;
    }

}
